﻿#include "Random.h"

namespace XyNet
{
	XYNET_IMPLEMENT_DEFAULT_OBJECT(Random);

	Random::Random() : _randomGenerator(std::random_device()())
	{
	}

	Random::Random(int seed) : _randomGenerator((unsigned)seed)
	{
	}

	int Random::nextInt()
	{
		return nextInt(0x7FFFFFFF);
	}

	int Random::nextInt(int maxValue)
	{
		return nextInt(0, maxValue);
	}

	int Random::nextInt(int minValue, int maxValue)
	{
		assert(minValue <= maxValue);
		if (minValue == maxValue)
			return maxValue;
		else
		{
			std::uniform_int_distribution<int> distribution(minValue, maxValue);
			return distribution(_randomGenerator);
		}
	}

	real Random::nextReal()
	{
		std::uniform_real_distribution<real> distribution(0, 1);
		return distribution(_randomGenerator);
	}

	void Random::nextBytes(Bytes* bytes)
	{
		std::uniform_int_distribution<short> distribution(0, 0xFF);
		for (size_t i = 0; i < bytes->size(); ++i)
		{
			bytes->at(i) = (byte)distribution(_randomGenerator);
		}
	}

	bool Random::isRandomHappen(real probability)
	{
		if (probability <= 0)
			return false;
		else if (probability >= 1 || probability > nextReal())
			return true;
		else
			return false;
	}
}